
import PoolManager from "../../manager/PoolManager";
import Unit from "../Unit";

const { ccclass, property } = cc._decorator;

/**
 * 子弹追踪
 */
@ccclass
export default class Bullet_Tracking extends cc.Component {

    /**
     * 目标
     */
    target: Unit = null;
    /**
     * 是否触发
     */
    fireFlag: boolean = false;
    /**
     * 子弹飞行速度
     */
    bulletSpeed = 400;
    /**
     * 子弹击中目标完成回调方法
     */
    callback: Function = null;
    targetPos
    /**
     * 发射子弹
     * @param unit 目标
     * @param callback 子弹击中目标完成回调方法
     */
    fire(unit: Unit, callback?: Function) {
        this.target = unit;
        this.callback = callback;
        this.node.active = true;
        this.fireFlag = true;
    }
    /**
     * 子弹击中目标
     */
    hitTheTarget() {
        if (this.callback) {
            this.callback();
            this.callback = null;
        }
        PoolManager.instance.put(this.node);
        this.fireFlag = false;
    }

    lateUpdate(dt) {
        if (!this.fireFlag) return;
        let p1 = this.node.getPosition();
        let target = this.target;
        if(!target) return;
        let p2 = cc.v2(target.pos.mul(target.world.gridEdge));
        let dir = p2.sub(p1);
        let normali = dir.normalize(cc.v2(1, 0));
        let angle = normali.signAngle(cc.v2(1, 0)) * 180 / Math.PI;
        this.node.angle = -angle - 90;
        let setp = (this.bulletSpeed / 60);
        this.node.x = this.node.x + setp * normali.x;
        this.node.y = this.node.y + setp * normali.y;

        let p3 = this.node.getPosition();
        let dir2 = p2.sub(p3);
        if (dir2.mag() <= setp) {
            this.fireFlag = false;
            this.hitTheTarget();
        }
    }
}